<template>
	<!-- 上传视频或者图片 -->
	<view class="up-page">
		<!--图片-->
		<view class="show-box" v-for="(item, index) in imageList" :key="index">
			<image
				class="full"
				:src="item.url"
				@tap="previewImage(item)"
			></image>
			<view
				class="delect-icon"
				v-if="!disabled"
				@tap="delect(index, item)"
			>
				<image class="full" :src="clearIcon" mode=""></image>
			</view>
		</view>
		<!--视频-->
		<view
			class="show-box"
			v-for="(item1, index1) in videoList"
			:key="index1"
		>
			<!-- <nVideo :src="item1.url" class="full"></nVideo> -->
			<!-- <video
				controls="true"
				:vslide-gesture-in-fullscreen="true"
				show-fullscreen-btn="true"
				class="full"
				:src="item1.url"
			></video> -->
			<DomVideoPlayer
				style="width: 100vw"
				:src="item1.url"
				:controls="true"
			/>
			<view
				v-if="!disabled"
				class="delect-icon"
				@tap="delectVideo(index1, item1)"
			>
				<image class="full" :src="clearIcon" mode=""></image>
			</view>
		</view>
		<view v-if="!disabled">
			<view
				v-if="VideoOfImagesShow"
				@tap="chooseVideoImage"
				class="box-mode"
			>
				<image class="full" :src="selectfile" mode=""></image>
			</view>
		</view>
	</view>
</template>
<script>
import config from '@/config';
const baseUrl = config.baseUrl;
import { getToken } from '@/utils/auth';
var sourceType = [['camera'], ['album'], ['camera', 'album']];
export default {
	components: {},
	props: {
		imgVideoLists: {
			type: Array,
			default: () => [],
		},
		//图片和视频允许上传的总数
		maxCount: {
			type: Number,
			default: 9,
		},
		disabled: {
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			fileImgType: ['png', 'jpg', 'bmp', 'jpeg', 'pdf', 'gif'],
			fileVideoType: [
				'mp4',
				'avi',
				'mov',
				'wmv',
				'mkv',
				'flv',
				'webm',
				'mpeg',
				'mpg',
			],
			// 图标
			clearIcon:
				'',
			selectfile:
				'',
			VideoOfImagesShow: true, // 页面图片或视频数量超出后，拍照按钮隐藏
			imageList: [], //存放图片的地址
			videoList: [], //视频存放的地址
			sourceType: ['拍摄'],
			sourceTypeIndex: 2,
			cameraList: [
				{
					value: 'back',
					name: '后置摄像头',
					checked: 'true',
				},
				{
					value: 'front',
					name: '前置摄像头',
				},
			],
			cameraIndex: 0, //上传视频时的数量

			delList: [],
		};
	},
	onUnload() {
		(this.imageList = []),
			(this.sourceTypeIndex = 2),
			(this.sourceType = ['拍摄']);
	},
	watch: {
		imageList: {
			handler(newVal) {
				this.$emit(
					'imgVideoList',
					newVal,
					this.videoList,
					this.delList.filter((item) => item.busId),
				);
			},
			deep: true,
		},
		videoList: {
			handler(newVal) {
				this.$emit(
					'imgVideoList',
					this.imageList,
					newVal,
					this.delList.filter((item) => item.busId),
				);
			},
			deep: true,
		},
		delList: {
			handler(newVal) {
				this.$emit(
					'imgVideoList',
					this.videoList,
					this.imageList,
					newVal.filter((item) => item.busId),
				);
			},
			deep: true,
		},
		imgVideoLists: {
			handler(newVal) {
				let fileName = null;
				this.imageList = newVal;
				// newVal.forEach((item) => {
				// 	// item.url = baseUrl + item.fileName;
				// 	// fileName = item.originalFileName.split('.');
				// 	const extension = this.getUrlExtension(item.url);
				// 	if (this.fileImgType.includes(extension)) {
				// 		this.imageList.push(item);
				// 	} else if (this.fileVideoType.includes(extension)) {
				// 		this.videoList.push(item);
				// 	}
				// });
			},
			immediate: true,
			deep: true,
		},
	},
	created() {
		console.log('created', this.disabled);
	},
	methods: {
		getUrlExtension(url) {
			// 处理无扩展名的情况
			if (!url.includes('.') || url.endsWith('/')) return '';

			// 处理带查询参数的URL
			const cleanUrl = url.split('?')[0];

			// 获取文件名部分
			const fileName = cleanUrl.substring(cleanUrl.lastIndexOf('/') + 1);

			// 处理多点文件名（如 image.min.js）
			const parts = fileName.split('.');
			if (parts.length > 1) return parts.pop().toLowerCase();

			return '';
		},
		//点击上传图片或视频
		chooseVideoImage() {
			if (this.disabled) return false;
			uni.showActionSheet({
				title: '选择上传类型',
				itemList: ['图片'],
				success: (res) => {
					console.log(res);
					if (res.tapIndex == 0) {
						this.chooseImages();
					} else {
						this.chooseVideo();
					}
				},
			});
		},
		//上传图片
		chooseImages() {
			uni.chooseImage({
				count: this.maxCount, //允许选择的数量
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				// sourceType: ['album', 'camera'], //从相册选择
				sourceType: ['camera'], //从相册选择
				success: async (res) => {
					const networkStatus = await this.$checkNetwork();
					for (let i = 0; i < res.tempFiles.length; i++) {
						if (res.tempFiles[i].size > 1024 * 5 * 1024) {
							uni.showToast({
								title: '图片大小不能超过5M',
								icon: 'none',
							});
							return;
						} else {
							console.log(networkStatus);
							// 如果没网络
							if (networkStatus === 'disconnected') {
								const tempData = [
									{
										url: res.tempFilePaths[i],
										status: 'temp',
									},
								];
								this.imageList =
									this.imageList.concat(tempData);
							} else {
								uni.uploadFile({
									url: baseUrl + '/alone/uploadImages',
									name: 'file',
									filePath: res.tempFilePaths[i],
									// files: res.tempFilePaths,
									header: {
										// Authorization: 'Bearer ' + getToken(),
										userToken: getToken(),
									},
									success: (uploadFileRes) => {
										if (uploadFileRes.statusCode !== 200) {
											uni.showToast({
												title: uploadFileRes.errMsg,
												icon: 'none',
											});
										} else {
											const tempData = [
												{
													url: uploadFileRes.data,
												},
											];
											this.imageList =
												this.imageList.concat(tempData);
											if (
												this.imageList.length +
													this.videoList.length ==
												this.maxCount
											) {
												this.VideoOfImagesShow = false;
											}
										}
									},
									fail: (err) => {
										console.log('fail====>', err);
										uni.showToast({
											title: '上传失败',
											icon: 'none',
										});
									},
								});
							}
						}
					}
				},
			});
		},
		//上传视频
		chooseVideo(index) {
			uni.chooseVideo({
				maxDuration: 60, //拍摄视频最长拍摄时间，单位秒。最长支持 60 秒
				camera: this.cameraList[this.cameraIndex].value, //'front'、'back'，默认'back'
				sourceType: sourceType[this.sourceTypeIndex],
				success: (res) => {
					console.log('res====>', res);
					const videoFile = res.tempFilePath; // 获取选择的视频文件路径
					const videoSize = res.size; // 获取视频文件大小

					// 检查文件大小（设置为5M）
					if (videoSize > 1024 * 1024 * 50) {
						uni.showToast({
							title: '视频大小不能超过50M',
							icon: 'none',
						});
						return;
					} else {
						// 上传视频
						uni.uploadFile({
							url: baseUrl + '/alone/uploadImages',
							name: 'file',
							filePath: res.tempFilePath,
							header: {
								Authorization: 'Bearer ' + getToken(),
							},
							success: (uploadFileRes) => {
								if (uploadFileRes.statusCode !== 200) {
									uni.showToast({
										title: uploadFileRes.errMsg,
										icon: 'none',
									});
								} else {
									const tempData = [
										{
											url: uploadFileRes.data,
										},
									];
									this.videoList =
										this.videoList.concat(tempData);
									if (
										this.imageList.length +
											this.videoList.length ==
										this.maxCount
									) {
										this.VideoOfImagesShow = false;
									}
								}
							},
							error: (err) => {
								uni.showToast({
									title: '上传失败',
									icon: 'none',
								});
							},
						});
					}
				},
			});
		},
		//预览图片
		previewImage: function (e) {
			console.log(e);
			uni.previewImage({
				current: e.url, // 当前预览的图片 URL
				urls: this.imageList.map((img) => img.url), // 图片列表的 URLs
			});
		},
		// 删除图片
		delect(index, row) {
			uni.showModal({
				title: '提示',
				content: '是否要删除该图片',
				success: (res) => {
					if (res.confirm) {
						this.imageList.splice(index, 1);
						this.delList.push(row);
					}
					if (
						this.imageList.length + this.videoList.length ==
						this.maxCount
					) {
						this.VideoOfImagesShow = false;
					} else {
						this.VideoOfImagesShow = true;
					}
				},
			});
		},
		// 删除视频
		delectVideo(index, row) {
			uni.showModal({
				title: '提示',
				content: '是否要删除此视频',
				success: (res) => {
					if (res.confirm) {
						this.videoList.splice(index, 1);
						this.delList.push(row);
					}
					if (
						this.imageList.length + this.videoList.length ==
						this.maxCount
					) {
						this.VideoOfImagesShow = false;
					} else {
						this.VideoOfImagesShow = true;
					}
				},
			});
		},
	},
};
</script>
<style lang="scss">
/* 统一上传后显示的盒子宽高比 */
.box-mode {
	min-width: 24vw;
	width: auto;
	height: 24vw;
	border-radius: 8rpx;
	overflow: hidden;
	display: flex;
	flex-wrap: wrap;
}

.full {
	width: 100%;
	height: 100%;
}

.up-page {
	display: flex;
	flex-wrap: wrap;
	display: flex;
	width: 100%;
	// .show-box:nth-child(3n) {
	// 	margin-right: 0;
	// }
	.show-box {
		position: relative;
		margin-bottom: 1vw;
		margin-right: 1vw;
		@extend .box-mode;

		.delect-icon {
			height: 40rpx;
			width: 40rpx;
			position: absolute;
			right: 0rpx;
			top: 0rpx;
			z-index: 9;
		}
	}
}
</style>
